import { ROOT } from '@sker/core';
import { existsSync } from 'fs';
import { join } from 'path';
import { createClient, RedisClientType, RedisDefaultModules } from 'redis';
import { DependencyContainer } from 'tsyringe';
export interface RedisHandler<T> {
    (client: RedisClientType<RedisDefaultModules>): Promise<T>;
}
let redisClient: Map<number, any> = new Map()
const getRedis = async (injector: DependencyContainer, database: number) => {
    const client = redisClient.get(database)
    if (client) return await client;
    const root = injector.resolve(ROOT)
    const env = injector.resolve<any>('ENV')
    let config: any = {
        url: env.REDIS_URL
    }
    const jsonFile = join(`${root}`, 'data/plugins', `@sker/redis.json`)
    if (existsSync(jsonFile)) {
        const jsonConfig = require(jsonFile)
        config.url = jsonConfig.url || config.url;
    }
    const url = new URL(config.url)
    const _client = createClient({
        socket: {
            host: url.hostname,
            port: parseInt(url.port),
        },
        name: 'redis',
        username: url.username,
        database,
        password: url.password
    }).connect();
    redisClient.set(database, _client)
    return await _client;
}
export const useRedis = async <T>(injector: DependencyContainer, handler: RedisHandler<T>, database: number) => {
    const client = await getRedis(injector, database)
    return await handler(client as RedisClientType)
}
export default useRedis;
